//
//  AppDelegate.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "AppDelegate.h"
#import "BLLoginHomeViewController.h"
#import "TMNavgationViewController.h"
#import "TMLoginViewController.h"
#import "TMRegisterViewController.h"
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [SVProgressHUD setMaximumDismissTimeInterval:2];
    bool success =  [WXApi registerApp:wechatID];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [TMTabbarViewController new];
    //注册微信

    if (![STUserManger defult].userID.length) {
        STNavigationController * nav = [[TMNavgationViewController alloc] initWithRootViewController:[BLLoginHomeViewController new]];
        self.window.rootViewController = nav;
    }
    [self.window makeKeyAndVisible];
    
    EMOptions *options = [EMOptions optionsWithAppkey:IM_appKey];
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    [TMWechatSocietyManger.manger registerWechatWithAppId:wechatID];
  
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return [TencentOAuth HandleOpenURL:url];
   
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    [[TMAliPayManger manger] inAppDelegateDealOpenURL:url];
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [UIViewController.new.st_currentNavgationController popToRootViewControllerAnimated:YES];
            });

            [[NSNotificationCenter defaultCenter] postNotificationName:aliPayHandleNotifacation object:resultDic];
            NSString * status = resultDic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                [SVProgressHUD showSuccessWithStatus:[self hudFromCode:status]];
            }else{
                [SVProgressHUD showErrorWithStatus:[self hudFromCode:status]];
            }
        }];
    }
    return [TencentOAuth HandleOpenURL:url];
}
//处理支付宝
- (NSString*)hudFromCode:(NSString*)code{
    if ([code isEqualToString:@"9000"]) {
        return @"支付成功";
    }
    if ([code isEqualToString:@"8000"]) {
        return @"正在处理中";
    }
    if ([code isEqualToString:@"4000"]) {
        return @"订单支付失败";
    }
    if ([code isEqualToString:@"5000"]) {
        return @"重复请求，支付失败";
    }
    if ([code isEqualToString:@"6001"]) {
        return @"中途取消，支付失败";
    }
    if ([code isEqualToString:@"6002"]) {
        return @"网络连接错误";
    }
    if ([code isEqualToString:@"6004"]) {
        return @"支付结果未知";
    }
    return @"未知错误";
}
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIViewController.new.st_currentNavgationController popToRootViewControllerAnimated:YES];
    });
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSLog(@"%@",token);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信登录"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝了微信登录"];
        }
        if (resp.errCode == 0) {
            // [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
            NSString * url =   [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wechatID,wechatSecret,token];
            [self fetchWeChatOpenIdRequestWithUrl:url];
            // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信分享"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信分享"];
        }
        if (resp.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信分享成功"];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        if (pay.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信支付"];
        }
        if (pay.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信支付"];
        }
        if (pay.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信支付成功"];
        }
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark --NetWork Method
- (void)fetchWeChatOpenIdRequestWithUrl:(NSString*)url{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        if ([dic.allKeys containsObject:@"openid"]) {
            NSString * openid = dic[@"openid"];
            [self sendWechatLoginRequestWithOpenid:openid];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)sendWechatLoginRequestWithOpenid:(NSString*)openid{
    
    //没手机，去绑定手机
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    [dic setObject:openid forKey:@"openid"];
    [dic setObject:@"2" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/loginAction"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 
                                                 NSDictionary * dic = [responseObject valueForKey:@"data"];
                                                 if ([dic.allKeys containsObject:@"mobile"]) {
                                                     NSString * mobie = dic[@"mobile"];
                                                     if (mobie.length < 2) {
                                                         //没手机，去绑定手机
                                                         [SVProgressHUD showSuccessWithStatus:@"已绑定微信，请绑定手机号"];
                                                         TMRegisterViewController * vc = [TMRegisterViewController new];
                                                         vc.openid = openid;
                                                         vc.type = @"2";
                                                         UINavigationController * homeVc = (id)self.window.rootViewController;
                                                         [homeVc pushViewController:vc animated:YES];
                                                         
                                                         return ;
                                                     }else{
                                                         if ([dic.allKeys containsObject:@"uid"]) {
                                                             NSString * userId = dic[@"uid"];
                                                             [[STUserManger defult] updateUserID:userId];
                                                         }
                                                          //更换rootViewControol
                                                         [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
                                                         [UIApplication sharedApplication].keyWindow.rootViewController = [TMTabbarViewController new];
                                                         [[UIApplication sharedApplication].keyWindow st_showAnimationWithType:STAnimationTyperippleEffect duration:2];
                                                     }
                                                 }
                                                

                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

